package cn.k7g.alloy.core.objectmapper;

import cn.k7g.alloy.annotation.CodeLabelEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.reflect.MethodUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 序列化CodeLabelEnum
 * @author victor-wu
 * @date 2024年4月3日
 */
public class CodeLabelEnumSerializer extends JsonSerializer<Object> {
    private CodeLabelEnum codeEnum;

    public CodeLabelEnumSerializer(CodeLabelEnum codeEnum) {
        this.codeEnum = codeEnum;
    }

    @Override
    public void serialize(Object v, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (v == null) {
            jsonGenerator.writeNull();
            return;
        }
        jsonGenerator.writeObject(v);
        String label = "";
        try {
            Class value = this.codeEnum.value();
            Field codeField = value.getDeclaredField("code");
            codeField.setAccessible(true);
            Method valuesMethod = value.getMethod("values");
            Object[] enums = (Object[]) valuesMethod.invoke(null);
            for (Object item : enums) {
                Object code = codeField.get(item);
                if (v.equals(code)) {
                    label = (String) MethodUtils.invokeMethod(item, "getLabel");
                }
            }
        } catch (Exception e) {}
        jsonGenerator.writeStringField(jsonGenerator.getOutputContext().getCurrentName() + "Label", label);
    }
}
